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 9.6KB

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