Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

SshDaemon.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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.ByteArrayOutputStream;
  18. import java.io.File;
  19. import java.io.FileOutputStream;
  20. import java.io.IOException;
  21. import java.io.OutputStreamWriter;
  22. import java.net.InetSocketAddress;
  23. import java.security.KeyPair;
  24. import java.security.KeyPairGenerator;
  25. import java.security.PrivateKey;
  26. import java.text.MessageFormat;
  27. import java.util.List;
  28. import java.util.concurrent.atomic.AtomicBoolean;
  29. import net.i2p.crypto.eddsa.EdDSAPrivateKey;
  30. import org.apache.sshd.common.config.keys.KeyEntryResolver;
  31. import org.apache.sshd.common.io.IoServiceFactoryFactory;
  32. import org.apache.sshd.common.io.mina.MinaServiceFactoryFactory;
  33. import org.apache.sshd.common.io.nio2.Nio2ServiceFactoryFactory;
  34. import org.apache.sshd.common.util.security.SecurityUtils;
  35. import org.apache.sshd.common.util.security.bouncycastle.BouncyCastleSecurityProviderRegistrar;
  36. import org.apache.sshd.common.util.security.eddsa.EdDSASecurityProviderRegistrar;
  37. import org.apache.sshd.common.util.security.eddsa.OpenSSHEd25519PrivateKeyEntryDecoder;
  38. import org.apache.sshd.server.SshServer;
  39. import org.apache.sshd.server.auth.pubkey.CachingPublicKeyAuthenticator;
  40. import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
  41. import org.bouncycastle.crypto.util.OpenSSHPrivateKeyUtil;
  42. import org.bouncycastle.crypto.util.PrivateKeyFactory;
  43. import org.bouncycastle.openssl.jcajce.JcaMiscPEMGenerator;
  44. import org.bouncycastle.util.io.pem.PemObject;
  45. import org.bouncycastle.util.io.pem.PemWriter;
  46. import org.eclipse.jgit.internal.JGitText;
  47. import org.slf4j.Logger;
  48. import org.slf4j.LoggerFactory;
  49. import com.gitblit.Constants;
  50. import com.gitblit.IStoredSettings;
  51. import com.gitblit.Keys;
  52. import com.gitblit.manager.IGitblit;
  53. import com.gitblit.transport.ssh.commands.SshCommandFactory;
  54. import com.gitblit.utils.JnaUtils;
  55. import com.gitblit.utils.StringUtils;
  56. import com.gitblit.utils.WorkQueue;
  57. import com.google.common.io.Files;
  58. /**
  59. * Manager for the ssh transport. Roughly analogous to the
  60. * {@link com.gitblit.transport.git.GitDaemon} class.
  61. *
  62. */
  63. public class SshDaemon {
  64. private static final Logger log = LoggerFactory.getLogger(SshDaemon.class);
  65. private static final String AUTH_PUBLICKEY = "publickey";
  66. private static final String AUTH_PASSWORD = "password";
  67. private static final String AUTH_KBD_INTERACTIVE = "keyboard-interactive";
  68. private static final String AUTH_GSSAPI = "gssapi-with-mic";
  69. public static enum SshSessionBackend {
  70. MINA, NIO2
  71. }
  72. /**
  73. * 22: IANA assigned port number for ssh. Note that this is a distinct
  74. * concept from gitblit's default conf for ssh port -- this "default" is
  75. * what the git protocol itself defaults to if it sees and ssh url without a
  76. * port.
  77. */
  78. public static final int DEFAULT_PORT = 22;
  79. private final AtomicBoolean run;
  80. private final IGitblit gitblit;
  81. private final SshServer sshd;
  82. /**
  83. * Construct the Gitblit SSH daemon.
  84. *
  85. * @param gitblit
  86. * @param workQueue
  87. */
  88. public SshDaemon(IGitblit gitblit, WorkQueue workQueue) {
  89. this.gitblit = gitblit;
  90. IStoredSettings settings = gitblit.getSettings();
  91. // Ensure that Bouncy Castle is our JCE provider
  92. SecurityUtils.registerSecurityProvider(new BouncyCastleSecurityProviderRegistrar());
  93. if (SecurityUtils.isBouncyCastleRegistered()) {
  94. log.info("BouncyCastle is registered as a JCE provider");
  95. }
  96. // Add support for ED25519_SHA512
  97. SecurityUtils.registerSecurityProvider(new EdDSASecurityProviderRegistrar());
  98. if (SecurityUtils.isProviderRegistered("EdDSA")) {
  99. log.info("EdDSA is registered as a JCE provider");
  100. }
  101. // Generate host RSA and DSA keypairs and create the host keypair provider
  102. File rsaKeyStore = new File(gitblit.getBaseFolder(), "ssh-rsa-hostkey.pem");
  103. File dsaKeyStore = new File(gitblit.getBaseFolder(), "ssh-dsa-hostkey.pem");
  104. File ecdsaKeyStore = new File(gitblit.getBaseFolder(), "ssh-ecdsa-hostkey.pem");
  105. File eddsaKeyStore = new File(gitblit.getBaseFolder(), "ssh-eddsa-hostkey.pem");
  106. File ed25519KeyStore = new File(gitblit.getBaseFolder(), "ssh-ed25519-hostkey.pem");
  107. generateKeyPair(rsaKeyStore, "RSA", 2048);
  108. generateKeyPair(ecdsaKeyStore, "ECDSA", 256);
  109. generateKeyPair(eddsaKeyStore, "EdDSA", 0);
  110. FileKeyPairProvider hostKeyPairProvider = new FileKeyPairProvider();
  111. hostKeyPairProvider.setFiles(new String [] { ecdsaKeyStore.getPath(), eddsaKeyStore.getPath(), ed25519KeyStore.getPath(), rsaKeyStore.getPath(), dsaKeyStore.getPath() });
  112. // Configure the preferred SSHD backend
  113. String sshBackendStr = settings.getString(Keys.git.sshBackend,
  114. SshSessionBackend.NIO2.name());
  115. SshSessionBackend backend = SshSessionBackend.valueOf(sshBackendStr);
  116. System.setProperty(IoServiceFactoryFactory.class.getName(),
  117. backend == SshSessionBackend.MINA
  118. ? MinaServiceFactoryFactory.class.getName()
  119. : Nio2ServiceFactoryFactory.class.getName());
  120. // Create the socket address for binding the SSH server
  121. int port = settings.getInteger(Keys.git.sshPort, 0);
  122. String bindInterface = settings.getString(Keys.git.sshBindInterface, "");
  123. InetSocketAddress addr;
  124. if (StringUtils.isEmpty(bindInterface)) {
  125. addr = new InetSocketAddress(port);
  126. } else {
  127. addr = new InetSocketAddress(bindInterface, port);
  128. }
  129. // Create the SSH server
  130. sshd = SshServer.setUpDefaultServer();
  131. sshd.setPort(addr.getPort());
  132. sshd.setHost(addr.getHostName());
  133. sshd.setKeyPairProvider(hostKeyPairProvider);
  134. List<String> authMethods = settings.getStrings(Keys.git.sshAuthenticationMethods);
  135. if (authMethods.isEmpty()) {
  136. authMethods.add(AUTH_PUBLICKEY);
  137. authMethods.add(AUTH_PASSWORD);
  138. }
  139. // Keep backward compatibility with old setting files that use the git.sshWithKrb5 setting.
  140. if (settings.getBoolean("git.sshWithKrb5", false) && !authMethods.contains(AUTH_GSSAPI)) {
  141. authMethods.add(AUTH_GSSAPI);
  142. log.warn("git.sshWithKrb5 is obsolete!");
  143. log.warn("Please add {} to {} in gitblit.properties!", AUTH_GSSAPI, Keys.git.sshAuthenticationMethods);
  144. settings.overrideSetting(Keys.git.sshAuthenticationMethods,
  145. settings.getString(Keys.git.sshAuthenticationMethods, AUTH_PUBLICKEY + " " + AUTH_PASSWORD) + " " + AUTH_GSSAPI);
  146. }
  147. if (authMethods.contains(AUTH_PUBLICKEY)) {
  148. SshKeyAuthenticator keyAuthenticator = new SshKeyAuthenticator(gitblit.getPublicKeyManager(), gitblit);
  149. sshd.setPublickeyAuthenticator(new CachingPublicKeyAuthenticator(keyAuthenticator));
  150. log.info("SSH: adding public key authentication method.");
  151. }
  152. if (authMethods.contains(AUTH_PASSWORD) || authMethods.contains(AUTH_KBD_INTERACTIVE)) {
  153. sshd.setPasswordAuthenticator(new UsernamePasswordAuthenticator(gitblit));
  154. log.info("SSH: adding password authentication method.");
  155. }
  156. if (authMethods.contains(AUTH_GSSAPI)) {
  157. sshd.setGSSAuthenticator(new SshKrbAuthenticator(settings, gitblit));
  158. log.info("SSH: adding GSSAPI authentication method.");
  159. }
  160. sshd.setSessionFactory(new SshServerSessionFactory(sshd));
  161. sshd.setFileSystemFactory(new DisabledFilesystemFactory());
  162. sshd.setForwardingFilter(new NonForwardingFilter());
  163. sshd.setCommandFactory(new SshCommandFactory(gitblit, workQueue));
  164. sshd.setShellFactory(new WelcomeShell(gitblit));
  165. // Set the server id. This can be queried with:
  166. // ssh-keyscan -t rsa,dsa -p 29418 localhost
  167. String version = String.format("%s (%s-%s)", Constants.getGitBlitVersion().replace(' ', '_'),
  168. sshd.getVersion(), sshBackendStr);
  169. sshd.getProperties().put(SshServer.SERVER_IDENTIFICATION, version);
  170. run = new AtomicBoolean(false);
  171. }
  172. public String formatUrl(String gituser, String servername, String repository) {
  173. IStoredSettings settings = gitblit.getSettings();
  174. int port = sshd.getPort();
  175. int displayPort = settings.getInteger(Keys.git.sshAdvertisedPort, port);
  176. String displayServername = settings.getString(Keys.git.sshAdvertisedHost, "");
  177. if(displayServername.isEmpty()) {
  178. displayServername = servername;
  179. }
  180. if (displayPort == DEFAULT_PORT) {
  181. // standard port
  182. return MessageFormat.format("ssh://{0}@{1}/{2}", gituser, displayServername,
  183. repository);
  184. } else {
  185. // non-standard port
  186. return MessageFormat.format("ssh://{0}@{1}:{2,number,0}/{3}",
  187. gituser, displayServername, displayPort, repository);
  188. }
  189. }
  190. /**
  191. * Start this daemon on a background thread.
  192. *
  193. * @throws IOException
  194. * the server socket could not be opened.
  195. * @throws IllegalStateException
  196. * the daemon is already running.
  197. */
  198. public synchronized void start() throws IOException {
  199. if (run.get()) {
  200. throw new IllegalStateException(JGitText.get().daemonAlreadyRunning);
  201. }
  202. sshd.start();
  203. run.set(true);
  204. String sshBackendStr = gitblit.getSettings().getString(Keys.git.sshBackend,
  205. SshSessionBackend.NIO2.name());
  206. log.info(MessageFormat.format(
  207. "SSH Daemon ({0}) is listening on {1}:{2,number,0}",
  208. sshBackendStr, sshd.getHost(), sshd.getPort()));
  209. }
  210. /** @return true if this daemon is receiving connections. */
  211. public boolean isRunning() {
  212. return run.get();
  213. }
  214. /** Stop this daemon. */
  215. public synchronized void stop() {
  216. if (run.get()) {
  217. log.info("SSH Daemon stopping...");
  218. run.set(false);
  219. try {
  220. ((SshCommandFactory) sshd.getCommandFactory()).stop();
  221. sshd.stop();
  222. } catch (IOException e) {
  223. log.error("SSH Daemon stop interrupted", e);
  224. }
  225. }
  226. }
  227. static void generateKeyPair(File file, String algorithm, int keySize) {
  228. if (file.exists()) {
  229. return;
  230. }
  231. try {
  232. KeyPairGenerator generator = SecurityUtils.getKeyPairGenerator(algorithm);
  233. if (keySize != 0) {
  234. generator.initialize(keySize);
  235. log.info("Generating {}-{} SSH host keypair...", algorithm, keySize);
  236. } else {
  237. log.info("Generating {} SSH host keypair...", algorithm);
  238. }
  239. KeyPair kp = generator.generateKeyPair();
  240. // create an empty file and set the permissions
  241. Files.touch(file);
  242. try {
  243. JnaUtils.setFilemode(file, JnaUtils.S_IRUSR | JnaUtils.S_IWUSR);
  244. } catch (UnsatisfiedLinkError | UnsupportedOperationException e) {
  245. // Unexpected/Unsupported OS or Architecture
  246. }
  247. FileOutputStream os = new FileOutputStream(file);
  248. PemWriter w = new PemWriter(new OutputStreamWriter(os));
  249. if (algorithm.equals("ED25519")) {
  250. // This generates a proper OpenSSH formatted ed25519 private key file.
  251. // It is currently unused because the SSHD library in play doesn't work with proper keys.
  252. // This is kept in the hope that in the future the library offers proper support.
  253. AsymmetricKeyParameter keyParam = PrivateKeyFactory.createKey(kp.getPrivate().getEncoded());
  254. byte[] encKey = OpenSSHPrivateKeyUtil.encodePrivateKey(keyParam);
  255. w.writeObject(new PemObject("OPENSSH PRIVATE KEY", encKey));
  256. }
  257. else if (algorithm.equals("EdDSA")) {
  258. // This saves the ed25519 key in a file format that the current SSHD library can work with.
  259. // We call it EDDSA PRIVATE KEY, but that string is given by us and nothing official.
  260. PrivateKey privateKey = kp.getPrivate();
  261. if (privateKey instanceof EdDSAPrivateKey) {
  262. OpenSSHEd25519PrivateKeyEntryDecoder encoder = (OpenSSHEd25519PrivateKeyEntryDecoder)SecurityUtils.getOpenSSHEDDSAPrivateKeyEntryDecoder();
  263. EdDSAPrivateKey dsaPrivateKey = (EdDSAPrivateKey)privateKey;
  264. // Jumping through some hoops here, because the decoder expects the key type as a string at the
  265. // start, but the encoder doesn't put it in. So we have to put it in ourselves.
  266. ByteArrayOutputStream encos = new ByteArrayOutputStream();
  267. String type = encoder.encodePrivateKey(encos, dsaPrivateKey);
  268. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  269. KeyEntryResolver.encodeString(bos, type);
  270. encos.writeTo(bos);
  271. w.writeObject(new PemObject("EDDSA PRIVATE KEY", bos.toByteArray()));
  272. }
  273. else {
  274. log.warn("Unable to encode EdDSA key, got key type " + privateKey.getClass().getCanonicalName());
  275. }
  276. }
  277. else {
  278. w.writeObject(new JcaMiscPEMGenerator(kp));
  279. }
  280. w.flush();
  281. w.close();
  282. } catch (Exception e) {
  283. log.warn(MessageFormat.format("Unable to generate {0} keypair", algorithm), e);
  284. }
  285. }
  286. }