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.

SshTestGitServer.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. /*
  2. * Copyright (C) 2018, 2020 Thomas Wolf <thomas.wolf@paranor.ch> and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.junit.ssh;
  11. import java.io.ByteArrayInputStream;
  12. import java.io.IOException;
  13. import java.io.InputStream;
  14. import java.nio.file.Files;
  15. import java.nio.file.Path;
  16. import java.security.GeneralSecurityException;
  17. import java.security.KeyPair;
  18. import java.security.PublicKey;
  19. import java.text.MessageFormat;
  20. import java.util.ArrayList;
  21. import java.util.Collections;
  22. import java.util.List;
  23. import java.util.Locale;
  24. import org.apache.sshd.common.NamedResource;
  25. import org.apache.sshd.common.PropertyResolverUtils;
  26. import org.apache.sshd.common.SshConstants;
  27. import org.apache.sshd.common.config.keys.AuthorizedKeyEntry;
  28. import org.apache.sshd.common.config.keys.KeyUtils;
  29. import org.apache.sshd.common.config.keys.PublicKeyEntryResolver;
  30. import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
  31. import org.apache.sshd.common.session.Session;
  32. import org.apache.sshd.common.util.buffer.Buffer;
  33. import org.apache.sshd.common.util.security.SecurityUtils;
  34. import org.apache.sshd.common.util.threads.CloseableExecutorService;
  35. import org.apache.sshd.common.util.threads.ThreadUtils;
  36. import org.apache.sshd.server.ServerAuthenticationManager;
  37. import org.apache.sshd.server.ServerFactoryManager;
  38. import org.apache.sshd.server.SshServer;
  39. import org.apache.sshd.server.auth.UserAuth;
  40. import org.apache.sshd.server.auth.UserAuthFactory;
  41. import org.apache.sshd.server.auth.gss.GSSAuthenticator;
  42. import org.apache.sshd.server.auth.gss.UserAuthGSS;
  43. import org.apache.sshd.server.auth.gss.UserAuthGSSFactory;
  44. import org.apache.sshd.server.auth.keyboard.DefaultKeyboardInteractiveAuthenticator;
  45. import org.apache.sshd.server.command.AbstractCommandSupport;
  46. import org.apache.sshd.server.session.ServerSession;
  47. import org.apache.sshd.server.shell.UnknownCommand;
  48. import org.apache.sshd.server.subsystem.SubsystemFactory;
  49. import org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory;
  50. import org.eclipse.jgit.annotations.NonNull;
  51. import org.eclipse.jgit.lib.Repository;
  52. import org.eclipse.jgit.transport.ReceivePack;
  53. import org.eclipse.jgit.transport.RemoteConfig;
  54. import org.eclipse.jgit.transport.UploadPack;
  55. /**
  56. * A simple ssh/sftp git <em>test</em> server based on Apache MINA sshd.
  57. * <p>
  58. * Supports only a single repository. Authenticates only the given test user
  59. * against his given test public key. Supports fetch and push.
  60. * </p>
  61. *
  62. * @since 5.2
  63. */
  64. public class SshTestGitServer {
  65. @NonNull
  66. protected final String testUser;
  67. @NonNull
  68. protected final Repository repository;
  69. @NonNull
  70. protected final List<KeyPair> hostKeys = new ArrayList<>();
  71. protected final SshServer server;
  72. @NonNull
  73. protected PublicKey testKey;
  74. private final CloseableExecutorService executorService = ThreadUtils
  75. .newFixedThreadPool("SshTestGitServerPool", 2);
  76. /**
  77. * Creates a ssh git <em>test</em> server. It serves one single repository,
  78. * and accepts public-key authentication for exactly one test user.
  79. *
  80. * @param testUser
  81. * user name of the test user
  82. * @param testKey
  83. * <em>private</em> key file of the test user; the server will
  84. * only user the public key from it
  85. * @param repository
  86. * to serve
  87. * @param hostKey
  88. * the unencrypted private key to use as host key
  89. * @throws IOException
  90. * @throws GeneralSecurityException
  91. */
  92. public SshTestGitServer(@NonNull String testUser, @NonNull Path testKey,
  93. @NonNull Repository repository, @NonNull byte[] hostKey)
  94. throws IOException, GeneralSecurityException {
  95. this.testUser = testUser;
  96. setTestUserPublicKey(testKey);
  97. this.repository = repository;
  98. server = SshServer.setUpDefaultServer();
  99. // Set host key
  100. try (ByteArrayInputStream in = new ByteArrayInputStream(hostKey)) {
  101. SecurityUtils.loadKeyPairIdentities(null, null, in, null)
  102. .forEach((k) -> hostKeys.add(k));
  103. } catch (IOException | GeneralSecurityException e) {
  104. // Ignore.
  105. }
  106. server.setKeyPairProvider((session) -> hostKeys);
  107. configureAuthentication();
  108. List<SubsystemFactory> subsystems = configureSubsystems();
  109. if (!subsystems.isEmpty()) {
  110. server.setSubsystemFactories(subsystems);
  111. }
  112. configureShell();
  113. server.setCommandFactory((channel, command) -> {
  114. if (command.startsWith(RemoteConfig.DEFAULT_UPLOAD_PACK)) {
  115. return new GitUploadPackCommand(command, executorService);
  116. } else if (command.startsWith(RemoteConfig.DEFAULT_RECEIVE_PACK)) {
  117. return new GitReceivePackCommand(command, executorService);
  118. }
  119. return new UnknownCommand(command);
  120. });
  121. }
  122. private static class FakeUserAuthGSS extends UserAuthGSS {
  123. @Override
  124. protected Boolean doAuth(Buffer buffer, boolean initial)
  125. throws Exception {
  126. // We always reply that we did do this, but then we fail at the
  127. // first token message. That way we can test that the client-side
  128. // sends the correct initial request and then is skipped correctly,
  129. // even if it causes a GSSException if Kerberos isn't configured at
  130. // all.
  131. if (initial) {
  132. ServerSession session = getServerSession();
  133. Buffer b = session.createBuffer(
  134. SshConstants.SSH_MSG_USERAUTH_INFO_REQUEST);
  135. b.putBytes(KRB5_MECH.getDER());
  136. session.writePacket(b);
  137. return null;
  138. }
  139. return Boolean.FALSE;
  140. }
  141. }
  142. private List<UserAuthFactory> getAuthFactories() {
  143. List<UserAuthFactory> authentications = new ArrayList<>();
  144. authentications.add(new UserAuthGSSFactory() {
  145. @Override
  146. public UserAuth createUserAuth(ServerSession session)
  147. throws IOException {
  148. return new FakeUserAuthGSS();
  149. }
  150. });
  151. authentications.add(
  152. ServerAuthenticationManager.DEFAULT_USER_AUTH_PUBLIC_KEY_FACTORY);
  153. authentications.add(
  154. ServerAuthenticationManager.DEFAULT_USER_AUTH_KB_INTERACTIVE_FACTORY);
  155. authentications.add(
  156. ServerAuthenticationManager.DEFAULT_USER_AUTH_PASSWORD_FACTORY);
  157. return authentications;
  158. }
  159. /**
  160. * Configures the authentication mechanisms of this test server. Invoked
  161. * from the constructor. The default sets up public key authentication for
  162. * the test user, and a gssapi-with-mic authenticator that pretends to
  163. * support this mechanism, but that then refuses to authenticate anyone.
  164. */
  165. protected void configureAuthentication() {
  166. server.setUserAuthFactories(getAuthFactories());
  167. // Disable some authentications
  168. server.setPasswordAuthenticator(null);
  169. server.setKeyboardInteractiveAuthenticator(null);
  170. server.setHostBasedAuthenticator(null);
  171. // Pretend we did gssapi-with-mic.
  172. server.setGSSAuthenticator(new GSSAuthenticator() {
  173. @Override
  174. public boolean validateInitialUser(ServerSession session,
  175. String user) {
  176. return false;
  177. }
  178. });
  179. // Accept only the test user/public key
  180. server.setPublickeyAuthenticator((userName, publicKey, session) -> {
  181. return SshTestGitServer.this.testUser.equals(userName) && KeyUtils
  182. .compareKeys(SshTestGitServer.this.testKey, publicKey);
  183. });
  184. }
  185. /**
  186. * Configures the test server's subsystems (sftp, scp). Invoked from the
  187. * constructor. The default provides a simple SFTP setup with the root
  188. * directory as the given repository's .git directory's parent. (I.e., at
  189. * the directory containing the .git directory.)
  190. *
  191. * @return A possibly empty collection of subsystems.
  192. */
  193. @NonNull
  194. protected List<SubsystemFactory> configureSubsystems() {
  195. // SFTP.
  196. server.setFileSystemFactory(new VirtualFileSystemFactory() {
  197. @Override
  198. protected Path computeRootDir(Session session) throws IOException {
  199. return SshTestGitServer.this.repository.getDirectory()
  200. .getParentFile().getAbsoluteFile().toPath();
  201. }
  202. });
  203. return Collections
  204. .singletonList((new SftpSubsystemFactory.Builder()).build());
  205. }
  206. /**
  207. * Configures shell access for the test server. The default provides no
  208. * shell at all.
  209. */
  210. protected void configureShell() {
  211. // No shell
  212. server.setShellFactory(null);
  213. }
  214. /**
  215. * Adds an additional host key to the server.
  216. *
  217. * @param key
  218. * path to the private key file; should not be encrypted
  219. * @param inFront
  220. * whether to add the new key before other existing keys
  221. * @throws IOException
  222. * if the file denoted by the {@link Path} {@code key} cannot be
  223. * read
  224. * @throws GeneralSecurityException
  225. * if the key contained in the file cannot be read
  226. */
  227. public void addHostKey(@NonNull Path key, boolean inFront)
  228. throws IOException, GeneralSecurityException {
  229. try (InputStream in = Files.newInputStream(key)) {
  230. KeyPair pair = SecurityUtils
  231. .loadKeyPairIdentities(null,
  232. NamedResource.ofName(key.toString()), in, null)
  233. .iterator().next();
  234. addHostKey(pair, inFront);
  235. }
  236. }
  237. /**
  238. * Adds an additional host key to the server.
  239. *
  240. * @param key
  241. * {@link KeyPair} to add
  242. * @param inFront
  243. * whether to add the new key before other existing keys
  244. * @since 5.8
  245. */
  246. public void addHostKey(@NonNull KeyPair key, boolean inFront) {
  247. if (inFront) {
  248. hostKeys.add(0, key);
  249. } else {
  250. hostKeys.add(key);
  251. }
  252. }
  253. /**
  254. * Enable password authentication. The server will accept the test user's
  255. * name, converted to all upper-case, as password.
  256. */
  257. public void enablePasswordAuthentication() {
  258. server.setPasswordAuthenticator((user, pwd, session) -> {
  259. return testUser.equals(user)
  260. && testUser.toUpperCase(Locale.ROOT).equals(pwd);
  261. });
  262. }
  263. /**
  264. * Enable keyboard-interactive authentication. The server will accept the
  265. * test user's name, converted to all upper-case, as password.
  266. */
  267. public void enableKeyboardInteractiveAuthentication() {
  268. server.setPasswordAuthenticator((user, pwd, session) -> {
  269. return testUser.equals(user)
  270. && testUser.toUpperCase(Locale.ROOT).equals(pwd);
  271. });
  272. server.setKeyboardInteractiveAuthenticator(
  273. DefaultKeyboardInteractiveAuthenticator.INSTANCE);
  274. }
  275. /**
  276. * Starts the test server, listening on a random port.
  277. *
  278. * @return the port the server listens on; test clients should connect to
  279. * that port
  280. * @throws IOException
  281. */
  282. public int start() throws IOException {
  283. server.start();
  284. return server.getPort();
  285. }
  286. /**
  287. * Stops the test server.
  288. *
  289. * @throws IOException
  290. */
  291. public void stop() throws IOException {
  292. executorService.shutdownNow();
  293. server.stop(true);
  294. }
  295. /**
  296. * Sets the test user's public key on the server.
  297. *
  298. * @param key
  299. * to set
  300. * @throws IOException
  301. * if the file cannot be read
  302. * @throws GeneralSecurityException
  303. * if the public key cannot be extracted from the file
  304. */
  305. public void setTestUserPublicKey(Path key)
  306. throws IOException, GeneralSecurityException {
  307. this.testKey = AuthorizedKeyEntry.readAuthorizedKeys(key).get(0)
  308. .resolvePublicKey(null, PublicKeyEntryResolver.IGNORING);
  309. }
  310. /**
  311. * Sets the test user's public key on the server.
  312. *
  313. * @param key
  314. * to set
  315. *
  316. * @since 5.8
  317. */
  318. public void setTestUserPublicKey(@NonNull PublicKey key) {
  319. this.testKey = key;
  320. }
  321. /**
  322. * Sets the lines the server sends before its server identification in the
  323. * initial protocol version exchange.
  324. *
  325. * @param lines
  326. * to send
  327. * @since 5.5
  328. */
  329. public void setPreamble(String... lines) {
  330. if (lines != null && lines.length > 0) {
  331. PropertyResolverUtils.updateProperty(this.server,
  332. ServerFactoryManager.SERVER_EXTRA_IDENTIFICATION_LINES,
  333. String.join("|", lines));
  334. }
  335. }
  336. private class GitUploadPackCommand extends AbstractCommandSupport {
  337. protected GitUploadPackCommand(String command,
  338. CloseableExecutorService executorService) {
  339. super(command, ThreadUtils.noClose(executorService));
  340. }
  341. @Override
  342. public void run() {
  343. UploadPack uploadPack = new UploadPack(repository);
  344. String gitProtocol = getEnvironment().getEnv().get("GIT_PROTOCOL");
  345. if (gitProtocol != null) {
  346. uploadPack
  347. .setExtraParameters(Collections.singleton(gitProtocol));
  348. }
  349. try {
  350. uploadPack.upload(getInputStream(), getOutputStream(),
  351. getErrorStream());
  352. onExit(0);
  353. } catch (IOException e) {
  354. log.warn(
  355. MessageFormat.format("Could not run {0}", getCommand()),
  356. e);
  357. onExit(-1, e.toString());
  358. }
  359. }
  360. }
  361. private class GitReceivePackCommand extends AbstractCommandSupport {
  362. protected GitReceivePackCommand(String command,
  363. CloseableExecutorService executorService) {
  364. super(command, ThreadUtils.noClose(executorService));
  365. }
  366. @Override
  367. public void run() {
  368. try {
  369. new ReceivePack(repository).receive(getInputStream(),
  370. getOutputStream(), getErrorStream());
  371. onExit(0);
  372. } catch (IOException e) {
  373. log.warn(
  374. MessageFormat.format("Could not run {0}", getCommand()),
  375. e);
  376. onExit(-1, e.toString());
  377. }
  378. }
  379. }
  380. }