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

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