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.

SshDaemon.java 7.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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.transport.ssh;
  17. import java.io.File;
  18. import java.io.FileOutputStream;
  19. import java.io.IOException;
  20. import java.io.OutputStreamWriter;
  21. import java.net.InetSocketAddress;
  22. import java.security.KeyPair;
  23. import java.security.KeyPairGenerator;
  24. import java.text.MessageFormat;
  25. import java.util.concurrent.atomic.AtomicBoolean;
  26. import org.apache.sshd.SshServer;
  27. import org.apache.sshd.common.io.IoServiceFactoryFactory;
  28. import org.apache.sshd.common.io.mina.MinaServiceFactoryFactory;
  29. import org.apache.sshd.common.io.nio2.Nio2ServiceFactoryFactory;
  30. import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
  31. import org.apache.sshd.common.util.SecurityUtils;
  32. import org.bouncycastle.openssl.PEMWriter;
  33. import org.eclipse.jgit.internal.JGitText;
  34. import org.slf4j.Logger;
  35. import org.slf4j.LoggerFactory;
  36. import com.gitblit.Constants;
  37. import com.gitblit.IStoredSettings;
  38. import com.gitblit.Keys;
  39. import com.gitblit.manager.IGitblit;
  40. import com.gitblit.transport.ssh.commands.SshCommandFactory;
  41. import com.gitblit.utils.IdGenerator;
  42. import com.gitblit.utils.JnaUtils;
  43. import com.gitblit.utils.StringUtils;
  44. import com.google.common.io.Files;
  45. /**
  46. * Manager for the ssh transport. Roughly analogous to the
  47. * {@link com.gitblit.transport.git.GitDaemon} class.
  48. *
  49. */
  50. public class SshDaemon {
  51. private final Logger log = LoggerFactory.getLogger(SshDaemon.class);
  52. public static enum SshSessionBackend {
  53. MINA, NIO2
  54. }
  55. /**
  56. * 22: IANA assigned port number for ssh. Note that this is a distinct
  57. * concept from gitblit's default conf for ssh port -- this "default" is
  58. * what the git protocol itself defaults to if it sees and ssh url without a
  59. * port.
  60. */
  61. public static final int DEFAULT_PORT = 22;
  62. private final AtomicBoolean run;
  63. private final IGitblit gitblit;
  64. private final SshServer sshd;
  65. /**
  66. * Construct the Gitblit SSH daemon.
  67. *
  68. * @param gitblit
  69. */
  70. public SshDaemon(IGitblit gitblit, IdGenerator idGenerator) {
  71. this.gitblit = gitblit;
  72. IStoredSettings settings = gitblit.getSettings();
  73. // Ensure that Bouncy Castle is our JCE provider
  74. SecurityUtils.setRegisterBouncyCastle(true);
  75. // Generate host RSA and DSA keypairs and create the host keypair provider
  76. File rsaKeyStore = new File(gitblit.getBaseFolder(), "ssh-rsa-hostkey.pem");
  77. File dsaKeyStore = new File(gitblit.getBaseFolder(), "ssh-dsa-hostkey.pem");
  78. generateKeyPair(rsaKeyStore, "RSA", 2048);
  79. generateKeyPair(dsaKeyStore, "DSA", 0);
  80. FileKeyPairProvider hostKeyPairProvider = new FileKeyPairProvider();
  81. hostKeyPairProvider.setFiles(new String [] { rsaKeyStore.getPath(), dsaKeyStore.getPath(), dsaKeyStore.getPath() });
  82. // Client public key authenticator
  83. CachingPublicKeyAuthenticator keyAuthenticator =
  84. new CachingPublicKeyAuthenticator(gitblit.getPublicKeyManager(), gitblit);
  85. // Configure the preferred SSHD backend
  86. String sshBackendStr = settings.getString(Keys.git.sshBackend,
  87. SshSessionBackend.NIO2.name());
  88. SshSessionBackend backend = SshSessionBackend.valueOf(sshBackendStr);
  89. System.setProperty(IoServiceFactoryFactory.class.getName(),
  90. backend == SshSessionBackend.MINA
  91. ? MinaServiceFactoryFactory.class.getName()
  92. : Nio2ServiceFactoryFactory.class.getName());
  93. // Create the socket address for binding the SSH server
  94. int port = settings.getInteger(Keys.git.sshPort, 0);
  95. String bindInterface = settings.getString(Keys.git.sshBindInterface, "");
  96. InetSocketAddress addr;
  97. if (StringUtils.isEmpty(bindInterface)) {
  98. addr = new InetSocketAddress(port);
  99. } else {
  100. addr = new InetSocketAddress(bindInterface, port);
  101. }
  102. // Create the SSH server
  103. sshd = SshServer.setUpDefaultServer();
  104. sshd.setPort(addr.getPort());
  105. sshd.setHost(addr.getHostName());
  106. sshd.setKeyPairProvider(hostKeyPairProvider);
  107. sshd.setPublickeyAuthenticator(keyAuthenticator);
  108. sshd.setPasswordAuthenticator(new UsernamePasswordAuthenticator(gitblit));
  109. sshd.setSessionFactory(new SshServerSessionFactory());
  110. sshd.setFileSystemFactory(new DisabledFilesystemFactory());
  111. sshd.setTcpipForwardingFilter(new NonForwardingFilter());
  112. sshd.setCommandFactory(new SshCommandFactory(gitblit, idGenerator));
  113. sshd.setShellFactory(new WelcomeShell(settings));
  114. // Set the server id. This can be queried with:
  115. // ssh-keyscan -t rsa,dsa -p 29418 localhost
  116. String version = String.format("%s (%s-%s)", Constants.getGitBlitVersion().replace(' ', '_'),
  117. sshd.getVersion(), sshBackendStr);
  118. sshd.getProperties().put(SshServer.SERVER_IDENTIFICATION, version);
  119. run = new AtomicBoolean(false);
  120. }
  121. public String formatUrl(String gituser, String servername, String repository) {
  122. if (sshd.getPort() == DEFAULT_PORT) {
  123. // standard port
  124. return MessageFormat.format("{0}@{1}/{2}", gituser, servername,
  125. repository);
  126. } else {
  127. // non-standard port
  128. return MessageFormat.format("ssh://{0}@{1}:{2,number,0}/{3}",
  129. gituser, servername, sshd.getPort(), repository);
  130. }
  131. }
  132. /**
  133. * Start this daemon on a background thread.
  134. *
  135. * @throws IOException
  136. * the server socket could not be opened.
  137. * @throws IllegalStateException
  138. * the daemon is already running.
  139. */
  140. public synchronized void start() throws IOException {
  141. if (run.get()) {
  142. throw new IllegalStateException(JGitText.get().daemonAlreadyRunning);
  143. }
  144. sshd.start();
  145. run.set(true);
  146. String sshBackendStr = gitblit.getSettings().getString(Keys.git.sshBackend,
  147. SshSessionBackend.NIO2.name());
  148. log.info(MessageFormat.format(
  149. "SSH Daemon ({0}) is listening on {1}:{2,number,0}",
  150. sshBackendStr, sshd.getHost(), sshd.getPort()));
  151. }
  152. /** @return true if this daemon is receiving connections. */
  153. public boolean isRunning() {
  154. return run.get();
  155. }
  156. /** Stop this daemon. */
  157. public synchronized void stop() {
  158. if (run.get()) {
  159. log.info("SSH Daemon stopping...");
  160. run.set(false);
  161. try {
  162. ((SshCommandFactory) sshd.getCommandFactory()).stop();
  163. sshd.stop();
  164. } catch (InterruptedException e) {
  165. log.error("SSH Daemon stop interrupted", e);
  166. }
  167. }
  168. }
  169. private void generateKeyPair(File file, String algorithm, int keySize) {
  170. if (file.exists()) {
  171. return;
  172. }
  173. try {
  174. KeyPairGenerator generator = SecurityUtils.getKeyPairGenerator(algorithm);
  175. if (keySize != 0) {
  176. generator.initialize(keySize);
  177. log.info("Generating {}-{} SSH host keypair...", algorithm, keySize);
  178. } else {
  179. log.info("Generating {} SSH host keypair...", algorithm);
  180. }
  181. KeyPair kp = generator.generateKeyPair();
  182. // create an empty file and set the permissions
  183. Files.touch(file);
  184. try {
  185. JnaUtils.setFilemode(file, JnaUtils.S_IRUSR | JnaUtils.S_IWUSR);
  186. } catch (UnsatisfiedLinkError | UnsupportedOperationException e) {
  187. // Unexpected/Unsupported OS or Architecture
  188. }
  189. FileOutputStream os = new FileOutputStream(file);
  190. PEMWriter w = new PEMWriter(new OutputStreamWriter(os));
  191. w.writeObject(kp);
  192. w.flush();
  193. w.close();
  194. } catch (Exception e) {
  195. log.warn(MessageFormat.format("Unable to generate {0} keypair", algorithm), e);
  196. return;
  197. }
  198. }
  199. }