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

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